"""
Takes a gff3 formatted file, and adjusts the base positions
to the provided upstream and downstream offsets

@author:charles.hefer@gmail.com
"""
import optparse, sys

def modify_bases(position, offset, operation):
	if operation == "+":
		return str(int(position) + int(offset))
	if int(position) - int(offset) > 0:
		return str(int(position) - int(offset))
	return str(0)
		
	

def __main__():
	parser = optparse.OptionParser()
	parser.add_option("-i","--input", default=None, dest="input",
					help="The input gff3 file")
	parser.add_option("-u","--upstream", default=0, dest="upstream",
					help="Include this many additional bases upstream")
	parser.add_option("-d", "--downstream", default=0, dest="downstream",
					help="Include this many additional bases downstream")
	parser.add_option("-o", "--output", default=None, dest="output", 
					help="The output gff3 file, with adjusted positions")
	(options,args) = parser.parse_args()
	
	handle = open(options.input, "r")
	outfile = open(options.output, "w")
	for line in handle:
		if "gene" in line:
			cols = line.split()
			#get the start and end position
			if cols[6] == "+":
				#do the start position, add
				cols[3] = modify_bases(cols[3], options.upstream, "-")
				cols[4] = modify_bases(cols[4], options.downstream, "+")
			else: #and for the negative orientation
				cols[3] = modify_bases(cols[3], options.downstream, "-")
				cols[4] = modify_bases(cols[4], options.upstream, "+")
			line = "\t".join(cols) + "\n"
		outfile.write(line)
	handle.close()
	outfile.close()


if __name__=="__main__":
	__main__()